<?php
/**
 * TODO: eliminar el require_once
 */
require_once 'Beach.class.php';
require_once 'Equipment.class.php';

function listChildren($id) {
	$sql = 'select * from location where idParent = %d';
	$result = db_query($sql,$id);
	$children = array();
	while ($data = db_fetch_object($result)) {
		$children[] = array(
			'id'=>$data->id,
			'name'=>$data->name,
			'children'=>listChildren($data->id),
		);
	}
  return $children;
}
function flatListChildren($id) {
	$sql = 'select * from location where idParent = %d';
	$result = db_query($sql,$id);
	$children = array();
	while ($data = db_fetch_object($result)) {
		$children = array_merge($children, array($data->id));
		$children = array_merge($children, flatListChildren($data->id));
	}
  return $children;
}
function listBeaches($params){
	$sql = 'select distinct beach.id, beach.name, beach.latitude, beach.longitude, beach.idLocation, beach.idBeachAemet, beach.timestamp $$$$ where 1=1';
	if(isset($params['location'])){
		$result = db_query('select * from location where name like \'%s%%\'',$params['location']);
		$data = db_fetch_object($result);
		$locations = flatListChildren($data->id);
		$locations[] = $data->id;
		$locations = implode(', ',$locations);
		$sql .= ' and idLocation in ('.$locations.')';
	}
	if(isset($params['name'])){
		$sql .= ' and name like \'%%'.mysql_real_escape_string($params['name']).'%%\'';
	}
	if(isset($params['available'])){
		$sql2='select distinct beach.id from beach';
		$sql3=' where 1=1';
		foreach($params['available'] as $p){
			$sql2.=" left join equipation e$p on beach.id = e$p.idBeach and e$p.idType = $p";
			$sql3.=" and e$p.name is not null";
		}
		$result = db_query($sql2.$sql3);
		$results = array();
		while($row=db_fetch_array($result)){
			$results[]=$row['id'];
		}
		if($results){
			$results = implode(',',$results);
			$sql .= ' and id in ('.$results.')';
		} else {
			// Cal veure si no es tornen resultats perque no hi ha cap platja o per algun problema amb els params que venen de $_GET
			$sql .= ' and 1=0';
		}
	}
	if(isset($params['tmax'])){
		list($min,$max) = explode(':',$params['tmax'].'::');
		$sql .= ' and tMax between ' . check_plain($min) . ' and ' . check_plain($max); 
	
	}
	if(isset($params['swell'])){
		$sql .= ' and statusSwellAm = ' . $params['swell'] . ' and statusSwellPm = ' . $params['swell'];
	}
	if(isset($params['tmax']) || isset($params['swell'])){
		$from = "from forecast right join beach on forecast.idBeach = beach.id";
	}else {
		$from = "from beach";
	}
	$sql = str_replace('$$$$',$from,$sql);
	$sql .= ' order by beach.name limit 100';
	$result = db_query($sql);
	$results = array();
	while($beaches=db_fetch_array($result)){
		$p = new Beach();
		$p->setId($beaches['id']);
		$p->setLatitude($beaches['latitude']);
		$p->setLongitude($beaches['longitude']);
		$p->setIdLocation($beaches['idLocation']);
		$p->callback=url('marker/'.$beaches['id']);
		$p->setIdType(0);
		$p->setName($beaches['name']);
		$results[] = $p;
	}
	return $results;
}

function buscarPlaya($params) {
        /**
         * Diferenciarem segons el tipus de $param.
         * Si �s un array, estarem tractant amb geolocalitzacions.
         * Si �s un int, amb l'id del location i retornarem els seus fills sempre que 
         * tingui.
         * 
         * Si �s un string, buscarem per nom i retornarem els seus fills si en t�
         */
         
        switch($params){
            case is_array($params):
                return getGeoPosition(array("lat"=>"38.3461111111", "lon"=>"-0.4772222222", "distance"=>15));
            case is_string($params):
                return getBeachByName($params);
            case is_int($params):
                return getBeachById($params);
            default:
                return null;
        }
}

function beachRecursive($idParent, &$_playa){
     $sql = "select distinct(id) from location where idParent = {$idParent}";
     $result1 = db_query($sql);
    
     //estamos dentro de una ciudad
     if(mysql_num_rows($result1) == 0 ){
        $sql ="
                SELECT * 
                FROM beach
                WHERE idLocation = $idParent";

            $result2 = db_query($sql);

            while( $beaches = db_fetch_array($result2) ) {
                $p = new Beach();
                $p->setId($beaches['id']);
                $p->setLatitude($beaches['latitude']);
                $p->setLongitude($beaches['longitude']);
                $p->setIdLocation($beaches['idLocation']);
                $p->setIdType($beaches['idType']);
                $p->setName($beaches['name']);
                $_playa[$beaches['id']] = $p;
             }
        } else {
            while( $locations = db_fetch_array($result1) ) {
                beachRecursive($locations['id'], $_playa);
            }
           
        }
}

function getBeachByName($name) {
        $sql = "
            SELECT id, idParent
            FROM location
            WHERE name ='$name'";

    $result = db_query($sql);
    
    $_playa = array();
    while($r = db_fetch_array($result)){
        beachRecursive($r[id], $_playa);
    }
    
    return $_playa;
}

function getBeachById($id){
    $playa = array();
   
    $sql = "
        SELECT *
        FROM beach
        WHERE id = {$id}";
        
    $result = db_query($sql);
   
   if(mysql_num_rows($result) == 0){
       return 0;
   }
   
    $beaches = db_fetch_array($result);

    $playa[0] = new Beach();
    $playa[0]->setId($beaches['id']);
    $playa[0]->setLatitude($beaches['latitude']);
    $playa[0]->setLongitude($beaches['longitude']);
    $playa[0]->setIdLocation($beaches['idLocation']);
    $playa[0]->setIdType($beaches['idType']);
    $playa[0]->setName($beaches['name']);
   
    return $playa;
   
}

function getEquipationByPosition($geo){
    
    $equips = array();
    
    $sql="
        SELECT *, (6371 * acos( cos( radians($geo[latitud]) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($geo[longitud]) ) + sin( radians($geo[latitud]) ) * sin( radians( latitude ) ) ) ) AS distance 
        FROM equipation
        WHERE idType = $geo[type]
        HAVING distance < 3
        ORDER BY distance";
            
   $result = db_query($sql);
   $i = 0;
   
   while($equipment = db_fetch_array($result)){
    $equips[$i] = new Equipment();
    $equips[$i]->setId($equipment['id']);
    $equips[$i]->setName($equipment['name']);
    $equips[$i]->setIdType($equipment['idType']);
    $equips[$i]->setLatitude($equipment['latitude']);
    $equips[$i]->setLongitude($equipment['longitude']);
    $equips[$i]->setIdType($equipment['idType']);
    $equips[$i]->callback=url('marker/'.$equipment['id']);
    $i++;
   }
   
   return $equips;
}
